import { ref, onMounted } from "vue";
import { useApi } from "./open.js";
import { useStore } from "vuex";

export const useChatManager = () => {
  const list = ref([]);
  const inputValue = ref("");
  const userid = ref(0);
  const ws = ref(null);

  const [getChatList, sendChat, uploadChat, cancelChat, searchChat] = useApi([
    "getChatList",
    "sendChat",
    "uploadChat",
    "cancelChat",
    "searchChat",
  ]);

  const sendMessage = async () => {
    const messageContent = inputValue.value.trim();
    if (messageContent) {
      const response = await sendChat({
        senderId: userid.value,
        receiverId: "", /* 根据需要设置接收者ID */
        type: "text",
        content: messageContent,
      });
      inputValue.value = "";
      if (ws.value) {
        ws.value.send(JSON.stringify(response.data));
      }
      list.value.push(response.data);
    }
  };

  const uploadFile = async (file) => {
    const formData = new FormData();
    formData.append('file', file);
    const response = await uploadChat({
      senderId: userid.value,
      receiverId: "", /* 根据需要设置接收者ID */
      file: formData,
    });
    if (ws.value) {
      ws.value.send(JSON.stringify(response.data));
    }
    list.value.push(response.data);
  };

  const deleteMessage = async (messageId) => {
    const response = await cancelChat({ id: messageId });
    if (response.success) {
      list.value = list.value.filter((message) => message.id !== messageId);
    }
  };

  const searchMessages = async (keyword, startDate, endDate) => {
    const response = await searchChat({
      mid: userid.value,
      keyword,
      startDate,
      endDate,
      page: 1,
      size: 10,
      sort: 0,
    });
    list.value = response.data.list;
  };

  const connectWebSocket = () => {
    ws.value = new WebSocket("ws://175.27.139.238:8088/stream?token=AiMj1yxucJ8rVOB");

    ws.value.onopen = () => {
      console.log("Connected to WebSocket server");
    };

    ws.value.onmessage = (event) => {
      console.log("Message received:", event.data);
      list.value.push(JSON.parse(event.data));
    };

    ws.value.onclose = () => {
      console.log("Disconnected from WebSocket server");
    };

    ws.value.onerror = (error) => {
      console.log("WebSocket error:", error);
    };
  };

  onMounted(async () => {
    userid.value = useStore.getters["user/getUserId"] || 0;
    const res = await getChatList({ mid: userid.value, page: 1, size: 10 });
    list.value = res.data;

    connectWebSocket();
  });

  return {
    list,
    inputValue,
    sendMessage,
    uploadFile,
    deleteMessage,
    searchMessages,
  };
};
